package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;


import com.aliyun.gts.bpaas.middleware.mq.api.model.MqPayload;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.MqMessageContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.ProcessItem;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.enums.MqProcessTypeEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.application.config.MqRunnerTask;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.SpringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.event.ProcessInstanceStartEvent;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ProcessInstanceStartHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;


import java.util.Objects;

/**
 * @author lzb
 * @date 2021/11/17 下午2:44
 */
@Slf4j
@Service
public class RecordProcessMessageHandler implements ProcessInstanceStartHandler {


    @Override
    public void handle(ProcessInstanceStartEvent event) {
        ProcessItem processItem = new ProcessItem();
        processItem.setProcessInstanceId(event.getProcessInstance().getProcessInstanceId());//流程实例id
        processItem.setProcessInstanceName(event.getProcessDefinition().getName());//流程名称
        processItem.setDeployId(event.getProcessDefinition().getDeploymentId());//部署id
        processItem.setProcessInstanceKey(event.getProcessDefinition().getKey());//流程编码
        processItem.setProcessInstanceVersion(String.valueOf(event.getProcessDefinition().getVersion()));//流程版本
        if (Objects.nonNull(event.getUser())) {
            processItem.setApplyUserId(event.getUser().getUserCode());//发起人id
            processItem.setApplyUserName(event.getUser().getUserName());//发起人名称
            processItem.setApplyUserType(event.getUser().getUserType());//发起人类型

        }
        try {
            MqMessageContext messageContext = MqMessageContext.builder().payload(MqPayload.make(processItem))
                    .tag(MqProcessTypeEnum.START.getType())
                    .messageKey(event.getProcessInstance().getProcessInstanceId())
                    .build();
            //这里可以走异步，前面拼接参数还是得同步
            doSendMessage(messageContext);
        } catch (Throwable e) {
            log.error("build messageContext error:",e);
        }
    }

    private void doSendMessage(MqMessageContext messageContext) {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringUtils.getBean(ThreadPoolTaskExecutor.class);
        threadPoolTaskExecutor.execute(new MqRunnerTask(SpringUtils.getBean(MqProducer.class),messageContext));
    }


}

